package part20IO流;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.jupiter.api.Test;

public class 对象流_序列化和反序列化 {
	
	@Test
	public void 写操作() {
		
		File file = new File("personinfo.txt");
		// 文件输出流
		FileOutputStream fos = null;
		// 对象输出流
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			
			// 将对象写入流中
			Person person = new Person("yy", "18");
			oos.writeObject(person); // 要做序列化的对象的类必须实现序列化接口
			
			System.out.println("----写入完毕 对象序列化成功---");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (oos!=null) {
					oos.close();
				}
				if (fos!=null) {
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Test
	public void 读操作() {
		// 文件输入流
		FileInputStream fis = null;
		// 对象输入流
		ObjectInputStream ois = null;
		try {
		
			fis = new FileInputStream("personinfo.txt");
			ois = new ObjectInputStream(fis);
			
			// 从流中读取对象信息  
			Person readObject = (Person) ois.readObject();
			System.out.println(readObject);
			
			System.out.println("----读取完毕 对象反序列化成功---");
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				if (ois!=null) {
					ois.close();
				}
				if (fis!=null) {
					fis.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

